package com.adjy.pathbuilders.touch;

import android.util.Log;

import com.adjy.pathbuilders.objects.Apple;
import com.adjy.pathbuilders.objects.Box;
import com.adjy.pathbuilders.objects.Cloud;
import com.adjy.pathbuilders.objects.GameEntityType;
import com.adjy.pathbuilders.objects.Spring;
import com.adjy.pathbuilders.rendering.AnimationPack;
import com.adjy.pathbuilders.rendering.DisplayConverter;
import com.adjy.pathbuilders.rendering.GameCanvas;
import com.adjy.pathbuilders.rendering.Point;
import com.adjy.pathbuilders.rendering.Renderable;
import com.adjy.pathbuilders.world.GameEntity;

public class TouchableObject implements Renderable {
	
	private static final float SECONDS_TO_MOVE = 0.5f;
	
	private float x, y;
	private float initialX, initialY;
	private GameEntityType type;
	private AnimationPack animation;
	
	private boolean moving;
	private float secondsLeftToMove;
	
	private GameEntity entity;
	
	public TouchableObject(float x, float y, GameEntityType type, AnimationPack ap) {
		this.x = x;
		this.y = y;
		this.initialX = x;
		this.initialY = y;
		this.type = type;
		this.animation = ap;
		createEntity(false);
	}
	
	public Point getCenter() {
		return new Point(x, y);
	}
	
	public void step(float timeElapsed) {
		if (moving) {
			secondsLeftToMove = secondsLeftToMove - timeElapsed;
			float numberOfStepsLeft = secondsLeftToMove / timeElapsed;
			if (secondsLeftToMove <= 0) {
				x = initialX;
				y = initialY;
				moving = false;
			} else {
				x += (initialX - x) / numberOfStepsLeft;
				y += (initialY - y) / numberOfStepsLeft;
			}
			
			// X, Y are Touch Current Position
			Point pos = DisplayConverter.convertFromDeviceScreen(x, y, true);
			entity.setX((int) pos.getX());
			entity.setY((int) pos.getY());
		}
	}

	@Override
	public void render(GameCanvas canvas, float timeElapsed) {
		entity.render(canvas, timeElapsed);
	}

	public void setPosition(float x, float y) { // X, Y are Touch Current Position
		this.x = x;
		this.y = y;
	}

	public void resetPosition() {
		moving = true;
		secondsLeftToMove = SECONDS_TO_MOVE;
	}

	public GameEntityType getType() {
		return type;
	}
	
	public GameEntity createEntity(boolean overrideOld) {
		
		Point pWorldPosition = DisplayConverter.convertFromDeviceScreen(
				this.x, this.y, true);
		
		int x = (int) pWorldPosition.getX();
		int y = (int) pWorldPosition.getY();
		
		if (entity == null || overrideOld) {
			
			switch (type) {
				case CLOUD:
					entity = new Cloud(x, y, animation);
					break;
				case BOX:
					entity = new Box(x, y, animation);
					break;
				case APPLE:
					entity = new Apple(x, y, animation);
					break;
				case SPRING:
					entity = new Spring(x, y, animation);
					break;
				default:
					Log.e("TouchableObject.createEntity", "EntityType not Listed");
			}
		} else {
			entity.setX(x);
			entity.setY(y);
		}
		
		return entity; 
	}
}
